<?php

App::uses('AppController', 'Controller');

class CategoriesController extends AppController {

	/**
	 * This controller does not use a model
	 *
	 * @var array
	 */
	public $uses = array('Category');

	public function index($type = null) {
		$conditions = array();
		if (null !== $type) {
			$conditions['type'] = $type;
		}
		$list = $this->Category->find('all', array('conditions' => $conditions, 'order' => 'name asc'));

		//Return $list if request is from requestAction of view element
		if ($this->request->is('requested')) {
			return $list;
		}

		$this->set('list', $list);
	}

	public function edit($id = null) {
		if ($this->request->is('post') || $this->request->is('put')) {
			$data = $this->request->data['Category'];
			if (null == $id) {
				$this->Category->create();
				$item = $this->Category->save($data);
			} else {
				$item = $this->Category->updateAll($data, array('Category.id' => $data));
			}
			if ($item) {
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('Thất bại!');
			}
		} else {
			if (null != $id) {
				if (!$this->request->data) {
					$this->request->data = $this->Category->findById($id);
				}
			} else {
				$this->request->data = array('Category' => array('type' => AppConstants::TRANSACTION_TYPE_EXPENSE));
			}
		}
	}

	public function delete($id) {
		if ($this->request->is('post')) {
			$this->Category->delete($id);
		}
		$this->redirect(array('action' => 'index'));
	}

}
